<template>
    <view class="container">
      <view class="title">学习进度</view>
      
      <view v-if="!hasApprovedEnrollment" class="tip-card card">
        <text>您还没有通过的报名申请，无法查看学习进度</text>
        <button class="btn-primary" size="mini" @click="navigateTo('/pages/enrollment/apply/apply')">立即报名</button>
      </view>
      
      <block v-else>
        <view class="progress-card card">
          <view class="progress-title">总体进度</view>
          <view class="progress-container">
            <progress :percent="totalProgress" stroke-width="14" color="#3c8dbc" />
            <view class="progress-percent">{{ totalProgress }}%</view>
          </view>
          
          <view class="progress-detail">
            <view class="progress-item" v-for="(subject, key) in subjectProgress" :key="key">
              <view class="progress-header">
                <text class="progress-name">{{ getSubjectName(key) }}</text>
                <text class="progress-status" :class="getStatusClass(subject.status)">
                  {{ getStatusText(subject.status) }}
                </text>
              </view>
              <view class="progress-bar">
                <progress :percent="getSubjectPercent(subject)" stroke-width="10" color="#67c23a" />
                <view class="progress-hours">{{ subject.hours }}学时</view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="record-container">
          <view class="record-header">
            <text class="record-title">学习记录</text>
            <text class="record-add" @click="showAddRecordModal">添加记录</text>
          </view>
          
          <view class="record-list">
            <view v-if="records.length === 0" class="empty-tip">
              暂无学习记录
            </view>
            
            <view class="record-item card" v-for="(item, index) in records" :key="index">
              <view class="record-info">
                <view class="record-subject">{{ getSubjectName(item.subject_type) }}</view>
                <view class="record-hours">{{ item.hours }}学时</view>
              </view>
              <view class="record-time">
                <text class="record-date">{{ formatDate(item.date) }}</text>
                <text class="record-coach" v-if="item.coach">教练：{{ item.coach.real_name }}</text>
              </view>
              <view class="record-content" v-if="item.content">
                {{ item.content }}
              </view>
            </view>
          </view>
        </view>
        
        <view class="exam-pass card">
          <view class="exam-pass-title">考试通过情况</view>
          <view class="exam-pass-list">
            <view 
              class="exam-pass-item" 
              v-for="(passed, key) in passedSubjects" 
              :key="key"
              :class="{ passed: passed }"
            >
              <text class="exam-pass-name">{{ getSubjectName(key) }}</text>
              <text class="exam-pass-status">{{ passed ? '已通过' : '未通过' }}</text>
            </view>
          </view>
        </view>
      </block>
      
      <!-- 添加学习记录弹窗 -->
      <uni-popup ref="addRecordPopup" type="bottom">
        <view class="add-record-container">
          <view class="add-record-title">添加学习记录</view>
          
          <view class="form-item">
            <view class="form-label">学习科目</view>
            <picker 
              mode="selector" 
              :range="subjectOptions" 
              range-key="name" 
              :value="subjectIndex" 
              @change="handleSubjectChange"
            >
              <view class="picker-value">
                {{ subjectOptions[subjectIndex].name }}
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <view class="form-label">学习日期</view>
            <picker 
              mode="date" 
              :value="recordForm.date" 
              :end="getCurrentDate()" 
              @change="handleDateChange"
            >
              <view class="picker-value">
                {{ recordForm.date || '请选择日期' }}
              </view>
            </picker>
          </view>
          
          <view class="form-item">
            <view class="form-label">学习时长(小时)</view>
            <input 
              class="input" 
              type="digit" 
              v-model="recordForm.hours" 
              placeholder="请输入学习时长" 
            />
          </view>
          
          <view class="form-item">
            <view class="form-label">学习内容</view>
            <textarea 
              class="textarea" 
              v-model="recordForm.content" 
              placeholder="请输入学习内容" 
            />
          </view>
          
          <view class="add-record-actions">
            <button class="btn-cancel" @click="hideAddRecordModal">取消</button>
            <button 
              class="btn-submit" 
              :loading="submitting" 
              :disabled="submitting" 
              @click="submitRecord"
            >
              提交
            </button>
          </view>
        </view>
      </uni-popup>
    </view>
  </template>
  
  <script>
  import { mapActions, mapGetters } from 'vuex';
  import { formatDate, getCurrentDate } from '@/utils/date';
  import { isEmpty } from '@/utils/validator';
  
  export default {
    data() {
      return {
        subjectOptions: [
          { value: 'subject1', name: '科目一（交通法规）' },
          { value: 'subject2', name: '科目二（场地驾驶）' },
          { value: 'subject3', name: '科目三（道路驾驶）' },
          { value: 'subject4', name: '科目四（安全文明）' }
        ],
        subjectIndex: 0,
        recordForm: {
          subject_type: 'subject1',
          date: getCurrentDate(),
          hours: '',
          content: ''
        },
        submitting: false
      };
    },
    computed: {
      ...mapGetters('enrollment', [
        'approvedEnrollments'
      ]),
      ...mapGetters('study', [
        'progress',
        'records',
        'totalProgress',
        'subjectProgress'
      ]),
      ...mapGetters('exam', [
        'passedSubjects'
      ]),
      hasApprovedEnrollment() {
        return this.approvedEnrollments && this.approvedEnrollments.length > 0;
      }
    },
    onLoad() {
      if (this.hasApprovedEnrollment) {
        // 获取学习进度
        this.getStudyProgress();
        
        // 获取学习记录
        this.getStudyRecords();
        
        // 获取考试通过情况
        this.getMyExamResults();
      }
    },
    methods: {
      ...mapActions('study', [
        'getStudyProgress',
        'getStudyRecords',
        'submitStudyRecord'
      ]),
      ...mapActions('exam', [
        'getMyExamResults'
      ]),
      navigateTo(url) {
        uni.navigateTo({
          url
        });
      },
      formatDate,
      getCurrentDate,
      getSubjectName(type) {
        const subjectMap = {
          'subject1': '科目一（交通法规）',
          'subject2': '科目二（场地驾驶）',
          'subject3': '科目三（道路驾驶）',
          'subject4': '科目四（安全文明）'
        };
        return subjectMap[type] || type;
      },
      getStatusText(status) {
        const statusMap = {
          'not_started': '未开始',
          'in_progress': '进行中',
          'completed': '已完成'
        };
        return statusMap[status] || status;
      },
      getStatusClass(status) {
        const classMap = {
          'not_started': 'status-not-started',
          'in_progress': 'status-in-progress',
          'completed': 'status-completed'
        };
        return classMap[status] || '';
      },
      getSubjectPercent(subject) {
        // 根据学时计算百分比，假设每个科目需要的总学时
        const totalHoursMap = {
          'subject1': 20,
          'subject2': 40,
          'subject3': 40,
          'subject4': 20
        };
        
        const totalHours = subject.status === 'completed' ? 100 : (totalHoursMap[subject.type] || 1);
        return Math.min(Math.round((subject.hours / totalHours) * 100), 100);
      },
      handleSubjectChange(e) {
        this.subjectIndex = e.detail.value;
        this.recordForm.subject_type = this.subjectOptions[this.subjectIndex].value;
      },
      handleDateChange(e) {
        this.recordForm.date = e.detail.value;
      },
      showAddRecordModal() {
        this.$refs.addRecordPopup.open();
      },
      hideAddRecordModal() {
        this.$refs.addRecordPopup.close();
      },
      submitRecord() {
        // 表单验证
        if (isEmpty(this.recordForm.subject_type)) {
          this.showToast('请选择学习科目');
          return;
        }
        
        if (isEmpty(this.recordForm.date)) {
          this.showToast('请选择学习日期');
          return;
        }
        
        if (isEmpty(this.recordForm.hours)) {
          this.showToast('请输入学习时长');
          return;
        }
        
        const hours = parseFloat(this.recordForm.hours);
        if (isNaN(hours) || hours <= 0 || hours > 12) {
          this.showToast('学习时长必须在0-12小时之间');
          return;
        }
        
        this.submitting = true;
        
        const recordData = {
          subject_type: this.recordForm.subject_type,
          date: this.recordForm.date,
          hours: hours,
          content: this.recordForm.content
        };
        
        this.submitStudyRecord(recordData)
          .then(() => {
            this.showToast('添加学习记录成功', 'success');
            this.hideAddRecordModal();
            
            // 重置表单
            this.recordForm = {
              subject_type: 'subject1',
              date: getCurrentDate(),
              hours: '',
              content: ''
            };
            this.subjectIndex = 0;
          })
          .catch(err => {
            this.showToast(err.message || '添加学习记录失败');
          })
          .finally(() => {
            this.submitting = false;
          });
      }
    }
  };
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .tip-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .progress-card {
    padding: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .progress-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20rpx;
  }
  
  .progress-container {
    margin-bottom: 30rpx;
  }
  
  .progress-percent {
    text-align: center;
    font-size: 24rpx;
    color: #3c8dbc;
    margin-top: 10rpx;
  }
  
  .progress-detail {
    margin-top: 30rpx;
  }
  
  .progress-item {
    margin-bottom: 30rpx;
  }
  
  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16rpx;
  }
  
  .progress-name {
    font-size: 28rpx;
    color: #333;
  }
  
  .progress-status {
    font-size: 24rpx;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
  }
  
  .status-not-started {
    background-color: #f0f0f0;
    color: #999;
  }
  
  .status-in-progress {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .status-completed {
    background-color: #e6f7f0;
    color: #52c41a;
  }
  
  .progress-bar {
    position: relative;
  }
  
  .progress-hours {
  position: absolute;
  right: 0;
  top: -6rpx;
  font-size: 24rpx;
  color: #999;
}

.record-container {
  margin-bottom: 30rpx;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.record-title {
  font-size: 32rpx;
  font-weight: bold;
}

.record-add {
  font-size: 28rpx;
  color: #3c8dbc;
}

.record-list {
  margin-bottom: 20rpx;
}

.empty-tip {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
}

.record-item {
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.record-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.record-subject {
  font-size: 30rpx;
  font-weight: bold;
}

.record-hours {
  font-size: 30rpx;
  color: #3c8dbc;
}

.record-time {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.record-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  padding-top: 16rpx;
  border-top: 1px solid #eee;
}

.exam-pass {
  padding: 30rpx;
}

.exam-pass-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.exam-pass-list {
  display: flex;
  justify-content: space-between;
}

.exam-pass-item {
  width: 22%;
  text-align: center;
  padding: 20rpx 0;
  border-radius: 8rpx;
  background-color: #f8f8f8;
}

.exam-pass-item.passed {
  background-color: #e6f7f0;
}

.exam-pass-name {
  display: block;
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.exam-pass-status {
  display: block;
  font-size: 24rpx;
  color: #999;
}

.exam-pass-item.passed .exam-pass-status {
  color: #52c41a;
}

.add-record-container {
  background-color: #fff;
  border-radius: 10rpx 10rpx 0 0;
  padding: 30rpx;
}

.add-record-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.picker-value {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.input {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.textarea {
  width: 100%;
  height: 180rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.add-record-actions {
  display: flex;
  justify-content: space-between;
}

.btn-cancel, .btn-submit {
  width: 48%;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 8rpx;
}

.btn-cancel {
  color: #666;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
}

.btn-submit {
  color: #fff;
  background-color: #3c8dbc;
}

.btn-primary {
  color: #fff;
  background-color: #3c8dbc;
}
</style>